package com.xianyun.site.iblog.gatewayimpl;

import com.alibaba.cola.exception.BizException;
import com.xianyun.site.iblog.domain.user.gateway.SocialUserGateway;
import com.xianyun.site.iblog.domain.user.model.SocialUser;
import com.xianyun.site.iblog.gatewayimpl.database.SocialUserMapper;
import com.xianyun.site.iblog.gatewayimpl.database.SystemUserMapper;
import com.xianyun.site.iblog.gatewayimpl.database.domainobject.SocialUserDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author mac_zyj
 */
@Slf4j
@Component
public class SocialUserGatewayImpl implements SocialUserGateway {

    @Autowired
    private SocialUserMapper socialUserMapper;

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Override
    public void checkAndInsertAuthToken(SocialUser socialUser) {
        SocialUserDO result= socialUserMapper.getSocialUserByUuid(socialUser.getUuid(), socialUser.getSource());
        if (null == result){
            result=new SocialUserDO();
        }
        socialUser.setId(result.getId());
        BeanUtils.copyProperties(socialUser,result,SocialUserDO.class);
        if (null != result.getId()){
            socialUserMapper.updateSocialUserInfo(result);
        }else {
            socialUserMapper.saveSocialUserInfo(result);
        }
    }

    @Override
    public void bindSocialUserAndUser(SocialUser socialUser) {
        int userId = Integer.parseInt(socialUser.getUserId());
        //判断是否可以查询到 三方账号绑定情况
        if (null != systemUserMapper.getSystemUserByUuidAndSource(socialUser.getUuid(), socialUser.getSource())){
            throw new BizException("该三方账号已绑定别的用户请确认");
        }
        //查询用户对应Source绑定情况 如果绑定Throw异常 否则 进行绑定
        if (null !=  socialUserMapper.getSocialUserByUid(socialUser.getUid(), socialUser.getSource())){
            throw new BizException("该用户已绑定同类型账号请勿重复绑定或解绑后再绑定!");
        }
        SocialUserDO socialResult= socialUserMapper.getSocialUserByUuid(socialUser.getUuid(), socialUser.getSource());
        socialUserMapper.saveUserLindWithSocial(socialResult.getId(),userId);
    }
}
